package org.shijiagen.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.shijiagen.constants.UserConstants;
import org.shijiagen.param.PageParam;
import org.shijiagen.param.UserCheckParam;
import org.shijiagen.param.UserLoginParam;
import org.shijiagen.pojo.User;
import org.shijiagen.user.mapper.UserMapper;
import org.shijiagen.user.service.UserService;
import org.shijiagen.utils.MD5Util;
import org.shijiagen.utils.R;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    @Override
    public Long check(UserCheckParam param) {
        return userMapper.selectCount(new QueryWrapper<User>().eq("user_name",param.getUserName()));
    }

    @Override
    public Boolean register(User user) {
        Long total = userMapper.selectCount(new QueryWrapper<User>().eq("user_name", user.getUserName()));
        if(total != 0){
            return false;
        }
        // 密码进行摘要算法处理防止撞库
        user.setPassword(MD5Util.encode(user.getPassword() + UserConstants.USER_SALT));
        // 查看返回结果，如果为0则插入失败
        int rows = userMapper.insert(user);
        return rows != 0;
    }

    @Override
    public User login(UserLoginParam loginParam) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("user_name", loginParam.getUserName())
                .eq("password", MD5Util.encode(loginParam.getPassword() + UserConstants.USER_SALT)));
    }

    @Override
    public R listPage(PageParam param) {
        Page<User> userPage = userMapper.selectPage(new Page<>(param.getCurrentPage(), param.getPageSize()), null);
        return R.ok("用户数据获取成功",userPage.getRecords(),userPage.getTotal());
    }

    @Override
    public R remove(Integer userId) {
        return userMapper.deleteById(userId) > 0 ? R.ok("用户数据删除成功") : R.fail("用户删除失败！");
    }

    @Override
    public R update(User user) {
        Long rows = userMapper.selectCount(new QueryWrapper<User>().eq("user_id", user.getUserId())
                .eq("password", user.getPassword()));
        if(rows == 0){
            user.setPassword(MD5Util.encode(user.getPassword()+UserConstants.USER_SALT));
        }
        return userMapper.updateById(user) > 0 ? R.ok("用户数据修改成功") : R.fail("用户数据修改失败");
    }

    @Override
    public R save(User user) {
        return register(user) ? R.ok("创建用户成功！") : R.fail("创建用户失败！");
    }
}
